package pl.mchaniewski.ryneczek.web;

import javax.faces.application.FacesMessage;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.FacesUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;

@Component
@Scope("request")
public class RegisterBean extends FormButton {
    private UserService userService;
    @Size(max = 30, message = "{registerbean.loginSize}")
    @Email(message = "{registerbean.loginEmail}")
    private String login;
    @Size(min = 5, max = 30, message = "{registerbean.passwordSize}")
    private String pass1;
    @Size(min = 5, max = 30, message = "{registerbean.passwordSize}")
    private String pass2;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPass1() {
        return pass1;
    }

    public void setPass1(String pass1) {
        this.pass1 = pass1;
    }

    public String getPass2() {
        return pass2;
    }

    public void setPass2(String pass2) {
        this.pass2 = pass2;
    }

    @PreAuthorize("isAnonymous()")
    public String validate() {
        if (!getPass1().equals(getPass2())) {
            FacesMessageUtil.addMessage(getButton(), I18nUtil
                    .getLocalizedMessage("changepasswordbean.doesntMatch"),
                    FacesMessage.SEVERITY_ERROR);
            return NavigationUtil.SAME_PAGE;
        }

        User user = userService.findByLogin(getLogin().toLowerCase());
        if (user != null) {
            FacesMessageUtil.addMessage(getButton(),
                    I18nUtil.getLocalizedMessage("registerbean.loginExists"),
                    FacesMessage.SEVERITY_ERROR);
        } else {
            if (userService.createNewUser(getLogin().toLowerCase(), getPass1()) != null) {
                FacesUtil.getFlashScope()
                        .put("login", getLogin().toLowerCase());

                return NavigationUtil.REGISTER_SUCCESS;
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("registerbean.createError"),
                        FacesMessage.SEVERITY_ERROR);
            }
        }

        return NavigationUtil.SAME_PAGE;
    }

}
